import jwt
from django.db.models.expressions import result
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed

from user.models import UserModel
from utils.MyJWT import  MyJWT


class MyAuthenticate(BaseAuthentication):
    def authenticate(self,request):
        myjwt = MyJWT()
        token = request.META.get('HTTP_AUTHORIZATION',None)
        if token:
            tokendata = token.split(' ')[1]
            try:
                result = myjwt.Checktoken(tokendata)
                user =UserModel.objects.filter(id=result.get('id')).first()
                return (user,tokendata)
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed('token过期')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed("token无效")
